package com.youlu.campus.service.activity.impl;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.ActivityUserAuthInfo;
import com.youlu.campus.service.activity.ActivityUserAuthInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class ActivityUserAuthInfoServiceImpl implements ActivityUserAuthInfoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ActivityUserAuthInfo find(@NotNull String userId, @NotNull String activityId) {
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId).and("activityId").is(activityId));
        ActivityUserAuthInfo info = mongoTemplate.findOne(query, ActivityUserAuthInfo.class);
        return info;
    }

    @Override
    public boolean craete(@NotNull ActivityUserAuthInfo req) {
        req.setCreatedTime(new Date());
        if (StringUtils.isBlank(req.getId())) {
            req.setId(null);
        }
        mongoTemplate.insert(req);
        return true;
    }

    @Override
    public boolean update(@NotNull ActivityUserAuthInfo req) {
        if (StringUtils.isBlank(req.getId())) {
            log.error(":>>> id为空");
            return false;
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        Update update = new Update();
        boolean updated = false;
        if (StringUtils.isNotBlank(req.getMobile())) {
            update.set("mobile", req.getMobile());
            updated = true;
        }
        if (Objects.nonNull(req.getCheckMobile())) {
            update.set("checkMobile", req.getCheckMobile());
            updated = true;
        }
        if (Objects.nonNull(req.getCheckMobileTime())) {
            update.set("checkMobileTime", req.getCheckMobileTime());
            updated = true;
        }
        if (updated) {
            update.set("updatedTime", new Date());
            UpdateResult result = mongoTemplate.updateFirst(query, update, ActivityUserAuthInfo.class);
            return result.getModifiedCount() > 0 ? true : false;
        }
        return false;
    }
}
